package com.eco.generator;

import com.eco.generator.domain.GenTable;
import com.eco.generator.util.VelocityInitializer;
import com.eco.generator.util.VelocityUtils;
import org.apache.commons.io.FileUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import pri.black.dogview.util.GenConstants;
import pri.black.dogview.util.StringUtils;

public class Gen {
    public static String getGenPath(GenTable table, String template)
    {
        String genPath = table.getGenPath();
        if (StringUtils.equals(genPath, "/"))
        {
            return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
        }
        return genPath + File.separator + VelocityUtils.getFileName(template, table);
    }


    private static void genSmall(String className, String moduleName, String functionName) throws Exception {
        VelocityInitializer.initVelocity();

        GenTable genTable = new GenTable();
        genTable.setPackageName("pri.black.garden");
        genTable.setClassName(className);
        genTable.setModuleName(moduleName);
        genTable.setBusinessName(functionName);
        genTable.setGenPath("/Users/black/Documents/project/dog-location-server/server/src/");
        genTable.setFunctionName(functionName);
        genTable.setFunctionAuthor("black");
        genTable.setTplCategory(GenConstants.TPL_CRUD);
        VelocityContext context = VelocityUtils.prepareSmallContext(genTable);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateSmallList();
        for (String template : templates)
        {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template);
            tpl.merge(context, sw);
//            System.out.println(sw);
            try
            {
                String path = getGenPath(genTable, template);
                System.out.println(path);

                FileUtils.writeStringToFile(new File(path), sw.toString());
            }
            catch (IOException e)
            {
                throw new Exception("渲染模板失败，表名：" + genTable.getTableName());
            }
            finally {

            }
        }
    }

    public static void main(String[] args) throws Exception {
        genSmall("PlanLog","garden","plan-log");
    }
}
